package com.example.student.security.handler;

import com.example.student.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    public JwtAuthenticationEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        // 从request中获取更详细的错误消息
        String errorMessage = (String) request.getAttribute("auth_error_message");
        if (errorMessage == null || errorMessage.isEmpty()) {
            // 如果没有自定义消息，尝试从异常中获取
            errorMessage = authException != null ? authException.getMessage() : null;
            
            // 如果异常消息也为空，使用默认消息
            if (errorMessage == null || errorMessage.isEmpty() || "Full authentication is required to access this resource".equals(errorMessage)) {
                errorMessage = "请先登录";
            } else if (errorMessage.contains("Bad credentials")) {
                errorMessage = "密码错误";
            } else if (errorMessage.contains("User is disabled")) {
                errorMessage = "账号已被禁用";
            } else if (errorMessage.contains("locked")) {
                errorMessage = "账号已被锁定";
            } else if (errorMessage.contains("expired")) {
                errorMessage = "登录已过期，请重新登录";
            }
        }

        Result<?> result = Result.unauthorized(errorMessage);
        objectMapper.writeValue(response.getWriter(), result);
    }
} 